<?php

/**
 * This is the model class for table "{{email_templates}}".
 *
 * The followings are the available columns in table '{{email_templates}}':
 * @property integer $zee_id
 * @property string $zee_title
 * @property string $zee_filename
 * @property string $zee_desc
 * @property string $zee_content
 * @property integer $zda_id
 * @property integer $inputtime
 * @property integer $updatetime
 */
class EmailTemplates extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return EmailTemplates the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{email_templates}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zda_id, inputtime, updatetime', 'numerical', 'integerOnly'=>true),
			array('zee_title, zee_filename', 'length', 'max'=>100),
			array('zee_desc', 'length', 'max'=>255),
			array('zee_content', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zee_id, zee_title, zee_filename, zee_desc, zee_content, zda_id, inputtime, updatetime', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
				'adminer'=>array(self::BELONGS_TO, 'Adminer', 'zda_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zee_id' => 'Zee',
			'zee_title' => 'Zee Title',
			'zee_filename' => 'Zee Filename',
			'zee_desc' => 'Zee Desc',
			'zee_content' => 'Zee Content',
			'zda_id' => 'Zda',
			'inputtime' => 'Inputtime',
			'updatetime' => 'Updatetime',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zee_id',$this->zee_id);
		$criteria->compare('zee_title',$this->zee_title,true);
		$criteria->compare('zee_filename',$this->zee_filename,true);
		$criteria->compare('zee_desc',$this->zee_desc,true);
		$criteria->compare('zee_content',$this->zee_content,true);
		$criteria->compare('zda_id',$this->zda_id);
		$criteria->compare('inputtime',$this->inputtime);
		$criteria->compare('updatetime',$this->updatetime);

		$criteria->order = " inputtime DESC ";//默认为时间倒序
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * 获取模板变量
	 */
	public function getVarUbb($type=null){
		if($type==null){
			return array(
				'{username}'=>'{username}',
				'{url}'=>'{url}',
				'{sitename}'=>'{sitename}',
				'{captcha}'=>'{captcha}',
				'{message}'=>'{message}',
			);
		}
	}
	
	/**
	 * 模板变量替换
	 */
	public function replaceVarUbb($str){
		$str = str_replace('{username}','<?php echo $params["username"]; ?>',$str);
		$str = str_replace('{url}','<?php echo $params["url"]; ?>',$str);
		$str = str_replace('{sitename}','<?php echo Yii::app()->name; ?>',$str);
		$str = str_replace('{captcha}','<?php echo $params["captcha"]; ?>',$str);
		$str = str_replace('{message}','<?php echo $params["message"]; ?>',$str);
		return $str;
	}
	
	/**
	 * 模板保存后的操作
	 * 写入模板文件
	 */
	protected function afterSave(){
		//获取邮件模板的目录路径
		$templatePath = $this->getTemplatesDir();
		$templatePath = $templatePath.$this->zee_filename.'.php';
		//文件写入
		$handle = fopen($templatePath, "wb");
		fwrite($handle, $this->replaceVarUbb($this->zee_content));
		fclose($handle);
	}
	
	/**
	 * 获取邮件模板的目录路径
	 */
	public function getTemplatesDir(){
		$templatePath = Yii::app()->mailer->pathViews;
		$templatePath = str_replace('application','',$templatePath);
		$templatePath = str_replace('.','/',$templatePath);
		$templatePath = Yii::app()->basePath.$templatePath.'/';
		return $templatePath;
	}
	
	/**
	 * 插入数据前的操作
	 */
	protected function beforeSave(){
		if($this->isNewRecord){
			$this->inputtime = time();
			$this->zda_id = Yii::app()->user->getid();
		}else{
			$this->updatetime = time();
		}
		return true;
	}
	
	/**
	 * 删除后的操作，删除模板文件
	 */
	protected function beforeDelete(){
		//获取邮件模板的目录路径
		$templatePath = $this->getTemplatesDir();
		$templatePath = $templatePath.$this->zee_filename.'.php';
		unlink($templatePath);
		return true;
	}
	
	/**
	 * 发送邮件
	 * @param $mid 会员ID
	 * @param $tid 邮件模板ID
	 * @param $params 邮件参数
	 */
	public function sentMail($mid,$tid,$params=array()){
		foreach((array)$mid as $id){
			$member = Member::model()->findByPk($id);
			$template = $this->findByPk($tid);
			
			$mailer = Yii::app()->mailer;
			if(Yii::app()->params['mailType'] == 'smtp'){
				$mailer->IsSMTP();
				$mailer->SMTPAuth = true;
			}
			$mailer->AddReplyTo($member->zm_email);
			$mailer->AddAddress($member->zm_email);
			$mailer->Subject = $template->zee_title;
			
			$params['username'] = isset($params['username'])?$params['username']:'';
			$params['url'] = isset($params['url'])?$params['url']:'';
			$params['captcha'] = isset($params['captcha'])?$params['captcha']:'';
			$params['message'] = isset($params['message'])?$params['message']:'';
			
			$mailer->getView($template->zee_filename, array('params'=>$params,'mailer'=>$mailer),'member');
			if($mailer->Send()){
				return true;
			}else{
				return false;
			}
		}
	}
	
	/**
	 * 邮件模板列表
	 */
	public function getTemplateData($type=null){
		if($type==null){
			$templates = $this->findAll();
			return CHtml::listData($templates,'zee_id','zee_title');
		}
	}
}